package cn.jinzhu.hystrix.service;

import cn.jinzhu.entity.User;
import com.netflix.hystrix.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

//请求合并最后一步，定义请求合并方法
public class UserCollpaseCommond  extends HystrixCollapser<List<User>, User, Integer> {
    private HelloService helloService;
    private Integer id;

    public UserCollpaseCommond(HelloService helloService, Integer id) {
        super(HystrixCollapser.Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("UserCollpaseCommond"))
        .andCollapserPropertiesDefaults(HystrixCollapserProperties.Setter().withTimerDelayInMilliseconds(200)));
        this.helloService = helloService;
        this.id = id;
    }

    @Override
    public Integer getRequestArgument() {
        return id;
    }

    @Override //请求合并方法
    protected HystrixCommand<List<User>> createCommand(Collection<CollapsedRequest<User, Integer>> collection) {
      List<Integer> ids = new ArrayList<>(collection.size());
      for(CollapsedRequest<User,Integer>userIntegerCollapsedRequest:collection){
          ids.add(userIntegerCollapsedRequest.getArgument());
      }
        return new UserBatchCommond(ids,helloService);
    }

    @Override//请求合并分发
    protected void mapResponseToRequests(List<User> users, Collection<CollapsedRequest<User, Integer>> collection) {
       int count = 0;
        for (CollapsedRequest<User, Integer> userIntegerCollapsedRequest : collection) {
            userIntegerCollapsedRequest.setResponse(users.get(count++));
        }
    }
}
